<template>
    <div class="application">
        <div class="application-heard">
            <a-input  v-model="keyword" STYLE="width: 400px;margin-right: 10px" :placeholder="$comi18('rxDialog.appName', '请输入应用名称','input')"  />
            <a-button @click="search()">
                {{$ti18('rxList.searchForBtn','搜索')}}
            </a-button>
            <div style="float: right">
                <a-button @click="appInstallList">
                    {{i18n('button.installation','应用安装列表')}}
                </a-button>
            </div>
        </div>
        <div class="application-tabb">
            <!--div class="copy"><a-icon type="switcher" /></div-->
            <a-tabs :defaultActiveKey="defaultKey"   @tabClick="tabClick" ref="tabs">
                <a-tab-pane v-for="(obj,index) of tabList" :key="obj.key" :tab="obj.CNAME + '(' + obj.CNT + ')'" >

                    <div class="application-LIST" v-for="app of obj.apps" :key="app.appId" @click="curAppId=app.appId" v-show="!app.hide">
                        <div>
                            <div v-if="app.share == 'Y' || app.tenantId == user.tenantId">
                                <div>
                                    <div class="app-icongont" :style="{'background':app.backColor}">
                                        <span v-show="false"> {{appIcon=JSON.parse(app.icon)}} </span>
                                        <em  v-if="['customIcon','userCustomIcon','jpaasIcon'].includes(appIcon.type)" >
                                            <my-icon :type="appIcon.icon"></my-icon>
                                        </em>
                                        <em v-else>
                                            <a-icon  :type="appIcon.icon" />
                                        </em>
                                        <span v-if="app.free=='Y'" class="iconfont-name">
                                            {{i18n('form.pay','付费')}}
                                            ({{app.share == 'Y' ? i18n('form.share','共享') : i18n('form.private','私有')}})
                                        </span>
                                        <span v-else="app.free=='N'" class="iconfont-name">
                                            {{i18n('form.free','免费')}}
                                            ({{app.share == 'Y' ? i18n('form.share','共享') : i18n('form.private','私有')}})
                                        </span>
                                    </div>
                                    <div class="app-type">{{app.clientName}}</div>
                                </div>
                            </div>
                            <div v-else>
                                <div>
                                    <div class="app-icongont" :style="{'background':app.backColor}">
                                        <span v-show="false"> {{appIcon=JSON.parse(app.icon)}} </span>
                                        <em  v-if="['customIcon','userCustomIcon','jpaasIcon'].includes(appIcon.type)" >
                                            <my-icon :type="appIcon.icon"></my-icon>
                                        </em>
                                        <em v-else>
                                            <a-icon  :type="appIcon.icon" />
                                        </em>
                                        <span v-if="app.free=='Y'" class="iconfont-name">
                                           {{i18n('form.pay','付费')}}
                                            ({{app.share == 'Y' ? i18n('form.share','共享') : i18n('form.private','私有')}})
                                        </span>
                                        <span v-else="app.free=='N'" class="iconfont-name">
                                            {{i18n('form.free','免费')}}
                                            ({{app.share == 'Y' ? i18n('form.share','共享') : i18n('form.private','私有')}})
                                        </span>
                                    </div>
                                    <div class="app-type">{{app.clientName}}</div>
                                </div>
                            </div>
                            <div class="app_button_list">
                                <a-tooltip placement="topLeft">
                                    <template slot="title" v-if="app.descp">
                                        <span>{{app.descp}}</span>
                                    </template>
                                    <div v-if="!judgeInstall(app.appId)">
                                        <span class="app_button" v-if="app.free == 'N' || (app.free == 'Y' && user.tenantId == app.tenantId)" @click="install(app)">
                                            {{i18n('form.install','安装')}}
                                        </span>
                                        <span class="app_button" v-else @click="buy(app)">
                                            {{i18n('form.purchase','购买')}}
                                        </span>
                                    </div>
                                    <div v-else>
                                        <span class="app_button_has_install">
                                            {{i18n('form.installed','已安装')}}
                                        </span>
                                    </div>
                                </a-tooltip>
                            </div>
                        </div>
                    </div>
                </a-tab-pane>
            </a-tabs>
        </div>
        <div class="application-tabb">
            <a-tabs ref="tabs">
                <a-tab-pane key="0" :tab="i18n('title.myApplication','我的应用 (') + myApp.length + ')'">
                    <vuedraggable :draggable="false">
                        <transition-group class="application-hover">
                            <div class="application-LIST" v-for="app of myApp" :key="app.appId" @click="curAppId=app.appId" v-show="!app.hide">
                                <a-popover v-model="app.visible" :title="i18n('title.menu','操作菜单')" trigger="click" placement="rightTop">
                                    <template slot="content">
                                        <ul class="app-set" v-if="curAppId==app.appId">
                                            <li v-if="app.status == 'Y'" @click="authorize(app)">
                                                {{i18n('button.empower','授权')}}
                                            </li>
                                            <li v-if="app.status == 'Y'" @click="startOrStop(app, 'N')">
                                                {{i18n('button.suspension','暂停使用')}}
                                            </li>
                                            <li v-if="app.status == 'N'" @click="startOrStop(app, 'Y')">
                                                {{i18n('button.useingBtn','启用')}}
                                            </li>
                                            <li @click="uninstall(app)">
                                                {{i18n('button.unloading','卸载')}}
                                            </li>
                                        </ul>
                                    </template>
                                    <div>
                                        <div class="app-icongont" :style="{'background': app.status == 'N' ? '#b8bfc3' : app.backColor}">
                                            <span v-show="false"> {{appIcon=JSON.parse(app.icon)}} </span>
                                            <em  v-if="['customIcon','userCustomIcon','jpaasIcon'].includes(appIcon.type)" >
                                                <my-icon :type="appIcon.icon"></my-icon>
                                            </em>
                                            <em v-else>
                                                <a-icon  :type="appIcon.icon" />
                                            </em>
                                            <span v-if="app.free=='Y'" class="iconfont-name">
                                                {{i18n('form.pay','付费')}}
                                             <span v-if="app.status == 'N'">
                                                 {{i18n('button.suspended','(已暂停)')}}
                                             </span></span>
                                            <span v-else="app.free=='N'" class="iconfont-name">
                                                {{i18n('form.free','免费')}}
                                            <span v-if="app.status == 'N'">
                                                 {{i18n('button.suspended','(已暂停)')}}
                                            </span></span>
                                        </div>
                                        <div class="app-type">{{app.clientName}}</div>
                                    </div>
                                </a-popover>
                            </div>
                        </transition-group>
                    </vuedraggable>
                </a-tab-pane>
            </a-tabs>
        </div>
        <div>
            <a-modal
                :title="i18n('title.installation','应用安装')"
                :visible="installVisible"
                :confirm-loading="confirmLoading"
                :maskClosable = "false"
                @ok="installTip"
                :width="width"
                @cancel="handleCancel">
                <div :class="modalContent">
                    <a-radio-group v-model="installType" default-value="1" button-style="solid" @change="radioChange">
                        <a-radio-button value="1">
                            {{i18n('radioMap.personal','个人安装')}}
                        </a-radio-button>
                        <a-radio-button value="2">
                            {{i18n('radioMap.tenant','为租户安装')}}
                        </a-radio-button>
                    </a-radio-group>
                    <div v-if="installType == 2" style="margin-top: 10px;">
                        <a-transfer
                            :data-source="instData"
                            :target-keys="targetKeys"
                            :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
                            :show-select-all="true"
                            @change="transferOnChange">
                            <template
                                slot="children"
                                slot-scope="{
                          props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
                          on: { itemSelectAll, itemSelect },}">
                                <a-table
                                    :row-selection="getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })"
                                    :columns="direction === 'left' ? leftColumns : rightColumns"
                                    :data-source="filteredItems"
                                    size="small"
                                    :style="{ pointerEvents: listDisabled ? 'none' : null }"
                                    :custom-row="({ key, disabled: itemDisabled }) => ({
                                        on: {
                                        click: () => {
                                          if (itemDisabled || listDisabled) return;
                                          itemSelect(key, !selectedKeys.includes(key));
                                        },
                                      },
                                    })"/>
                            </template>
                        </a-transfer>
                    </div>
                </div>
            </a-modal>
        </div>
    </div>
</template>

<script>
import vuedraggable from 'vuedraggable'
import SysAppApi from '@/api/system/core/sysApp'
import SysAppEdit from '@/views/modules/system/core/SysAppEdit'
import SysAppExport from "@/views/modules/system/core/SysAppExport";
import AppImport from '@/views/modules/system/core/AppImport';
import {Dialog, BaseList, Util} from "@lowcode/jpaas-common-lib";
import {mapState} from 'vuex';
import {difference} from 'lodash-es';

const leftTableColumns = [
    {
        dataIndex: 'instNo',
        title: this.i18n('radioMap.instNo','机构编号'),
    },
    {
        dataIndex: 'nameCn',
        title: this.i18n('radioMap.tenantName','租户名称'),
    },
];
const rightTableColumns = [
    {
        dataIndex: 'instNo',
        title: this.i18n('radioMap.instNo','机构编号'),
    },
    {
        dataIndex: 'nameCn',
        title: this.i18n('radioMap.tenantName','租户名称'),
    }
];
export default {
    name: "applicationindex",
    mixins: [BaseList],
    components:{
        vuedraggable,
        SysAppEdit,
        SysAppExport,
        AppImport
    },
    computed: {
        ...mapState({
            navigation: state => state.appSetting.navigation,
            user: (state) => state.appSetting.user,
        })
    },
    inject: ['reload'],
    data(){
        return {
            curAppId:'',
            defaultKey:'all',
            curKey:'all',
            keyword:'',
            tabList:[],
            component: SysAppEdit,
            comment: this.i18n('title.authorization','应用授权'),
            widthHeight: ['1000px', '680px'],
            // 我的APP
            myApp: [],
            myAppId: null,
            installVisible: false,
            confirmLoading: false,
            installType: "1",
            instData: [],
            targetKeys: [],
            leftColumns: leftTableColumns,
            rightColumns: rightTableColumns,
            width: "30%",
            modalContent: 'mix_content',
            installApp: null,
        }
    },
    mounted() {
        this.loadData();
        this.loadMyApp();
        setInterval(()=> {
            this.instData = [];
        }, 60000)
    },
    methods:{
        i18n(name, text, key) {
            return this.$ti18(name, text, "applicationLang", key);
        },
        // 判断是否已安装
        judgeInstall(appId) {
            let flag = false;
            for (let i = 0; i < this.myApp.length; i++) {
                if (appId == this.myApp[i].appId) {
                    flag = true;
                    break;
                }
            }
            return flag;
        },
        // 安装类型change时间
        radioChange(e) {
            if (e.target.value == '1') {
                this.width = "30%";
                this.modalContent = "min_content";
            } else {
                this.width = "80%";
                this.modalContent = "max_content";
            }
            this.targetKeys = [];
        },
        // 穿梭框选择时间
        transferOnChange(nextTargetKeys) {
            this.targetKeys = nextTargetKeys;
        },
        getRowSelection({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
            return {
                getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
                onSelectAll(selected, selectedRows) {
                    const treeSelectedKeys = selectedRows
                        .filter(item => !item.disabled)
                        .map(({ key }) => key);
                    const diffKeys = selected
                        ? difference(treeSelectedKeys, selectedKeys)
                        : difference(selectedKeys, treeSelectedKeys);
                    itemSelectAll(diffKeys, selected);
                },
                onSelect({ key }, selected) {
                    itemSelect(key, selected);
                },
                selectedRowKeys: selectedKeys,
            };
        },
        // 安装确认提示
        installTip () {
            let self_ = this;
            this.$confirm({
                title: self_.i18n('form.install','安装'),
                okType: 'info',
                content: self_.i18n('form.installApplication','确认安装应用吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    self_.handleOk();
                },
                cancel() {}
            });
        },
        // 对话框确认事件
        handleOk() {
            let param = {
                appId: this.installApp.appId,
                free: this.installApp.free,
                appName: this.installApp.clientName,
                enable: 'Y',
            }
            if (this.installType == '1') {
                if (this.user.admin) {
                    param.tenantId =  this.user.tenantId;
                } else {
                    param.userId =  this.user.userId;
                }
            } else {
                if (this.targetKeys.length == 0 ) {
                    this.$message.info(this.i18n('form.tenant','请选择租户！'))
                    return ;
                }
                param.tenantId = this.targetKeys.join(",");
                let instName = [];
                for (let i = 0; i < this.targetKeys.length; i++) {
                    for (let j = 0; j < this.instData.length; j++) {
                        if (this.targetKeys[i] == this.instData[j].key) {
                            instName.push(this.instData[j].nameCn);
                        }
                    }
                }
                param.instName = instName.join(",");
            }
            let self_ = this;
            this.confirmLoading = true;
            SysAppApi.installApp(param).then(res => {
                self_.confirmLoading = false;
                if(!res.success){
                    return ;
                }
                //self_.openMessage('success', "安装成功！");
                self_.installVisible = false;
                setTimeout(()=> {
                    location.reload();
                }, 500)
            })
        },
        // 对话框取消事件
        handleCancel() {
            this.installVisible = false;
        },
        // 授权
        authorize(app) {
            app.visible = false;
            let url = "/market/authorize?appId=" + app.appId + "&appName=" + app.clientName + "&appIcon=" + app.icon;
            this.$router.push(url);
        },
        // 授权
        appInstallList() {
            let url = "/market/appInstallList?appId=1&appName="+this.i18n('allApplications','所有应用');
            this.$router.push(url);
        },
        // 启用或暂停
        startOrStop(app, status) {
            let self_ = this;
            app.visible = false;
            app.enable = status;
            this.$confirm({
                title: status == 'Y' ? self_.i18n('radioMap.start','启动') : self_.i18n('radioMap.pause','暂停') ,
                okType: 'info',
                content: status == 'Y' ? self_.i18n('tips.startApplication','确认启动应用吗？'): self_.i18n('tips.pauseApplication','确认暂停应用吗？'),
                okText: self_.$ti18('rxForm.ackBtn','确认'),
                cancelText: self_.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    SysAppApi.startOrStop(app).then(res => {
                        if(!res.success){
                            self_.openMessage('error', res.message);
                            return ;
                        }
                        self_.openMessage('success', status == 'Y' ? self_.i18n('radioMap.successfulStartup','启动成功') : self_.i18n('radioMap.pauseSuccess','暂停成功') );
                        setTimeout(()=> {
                            location.reload();
                        }, 500)

                    })
                },
                cancel() {}
            });

        },
        // 卸载
        uninstall(app) {
            let self_ = this;
            app.visible = false;
            this.$confirm({
                title: self_.i18n('title.unloading','卸载'),
                okType: 'info',
                content: self_.i18n('title.uninstall','确认卸载应用吗？'),
                okText: self_.$ti18('rxForm.ackBtn','确认'),
                cancelText: self_.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    SysAppApi.uninstall(app).then(res => {
                        if(!res.success){
                            self_.openMessage('error', res.message);
                            return ;
                        }
                        self_.openMessage('success', self_.i18n('tips.uninstall','卸载成功！'));
                        setTimeout(()=> {
                            location.reload();
                        }, 500)
                    })
                },
                cancel() {}
            });
        },
        // 购买
        buy(app) {
            app.visible = false;
            alert(this.i18n('title.paid','付费应用，请联系管理员开通'))
        },
        // 安装应用
        install(app) {
            this.modalContent = 'mix_content';
            this.width = "30%";
            this.installApp = app;
            if (app.free === 'Y' && app.tenantId != this.user.tenantId) {
                this.$message.info(this.i18n('title.paid','付费应用，请联系管理员开通'));
                return ;
            }
            app.visible = false;
            this.installType = '1';
            // 屏蔽管理员为其它租户安装
            if (false && this.user.tenantId == 1 && this.user.admin == true) {
                this.installVisible = true;
                this.confirmLoading = false;
                let self_ = this;
                if (this.instData == 0) {
                    this.instData = [];
                    SysAppApi.getInstData().then(res => {
                        if(!res.success){
                            return ;
                        }
                        let data = res.data;
                        if (data) {
                            for (let i = 0; i < data.length; i++) {
                                let obj = data[i];
                                self_.instData.push(
                                    {
                                        key : obj.instId,
                                        nameCn : obj.nameCn,
                                        instNo : obj.instNo
                                    }
                                )
                            }
                        }
                    })
                }
            } else {
                // this.handleOk();
                this.installTip();
            }
        },
        // 打开提示框
        openMessage(type, msg) {
            this.$notification[type]({
                message:this.$ti18('rxMsa.actionTips','操作提示'),
                description: msg,
            });
        },
        // 加载我的应用
        loadMyApp() {
            let param = {};
            if (this.user.admin) {
                param.tenantId = this.user.tenantId;
            } else {
                param.userId = this.user.userId;
            }
            let self_ = this;
            SysAppApi.getMyApp(param).then(res => {
                if(!res.success){
                    self_.openMessage('error', res.message);
                    return ;
                }
                self_.myApp = res.data;
                self_.$nextTick(function (){
                    self_.$forceUpdate();
                });
            })
        },
        // 加载数据
        /*loadData(){
            console.log(this.user);
            let self_=this;
            //创建页面时加载数据
            SysAppApi.getAppMarketData().then(res => {
                console.log(res)
                if(!res.success){
                    self_.openMessage('error', res.message);
                    return ;
                }
                let data = res.data;
                // 付费
                let payCount = 0;
                let payData = [];
                // 免费
                let freeCount = 0;
                let freeData = [];
                for (let obj of data) {
                   if (obj.free === 'Y') {
                       payCount ++;
                       payData.push(obj);
                   } else {
                       freeCount ++;
                       freeData.push(obj);
                   }
                }
                // 全部数据
                let allDataList = {key: 'all',CID: 'all',CNAME: '全部',CNT: data.length, apps: data};
                // 付费数据
                let payDataList = {key: 'pay',CID: 'pay',CNAME: '付费',CNT: payCount, apps: payData};
                // 付费数据
                let noPayDataList = {key: 'free',CID: 'free',CNAME: '免费',CNT: freeCount, apps: freeData};
                self_.tabList.push(allDataList);
                self_.tabList.push(payDataList);
                self_.tabList.push(noPayDataList);
                this.$nextTick(function (){
                    this.$refs.tabs.onTabClick(this.curKey);
                });
            })
        },*/
        loadData(){
            let self_=this;
            //创建页面时加载数据
            SysAppApi.getCountByCategory().then(res => {
                if(!res.success){
                    self_.$message.error(res.message);
                    return ;
                }
                let data=res.data;
                //统计“全部”的数量，把各分类的数量加起来
                let cnt=0;
                for (let obj of data) {
                    obj.key=obj.CID;
                    obj.apps=[];
                    cnt =cnt +obj.CNT;
                }
                let first={key:'all',CID:'all',CNAME:self_.i18n('title.all','全部'),CNT:cnt, apps:[]};
                data.splice(0,0,first);
                this.tabList=data;
                this.getApps();
                this.$nextTick(function (){
                    this.$refs.tabs.onTabClick(this.curKey);
                });
            })
        },
        //查询应用数据
        getApps(){
            var self_=this;
            let params={CID:'-1'};
            //按分类加载应用数据
            SysAppApi.getByCategoryOrKey(params).then(res => {
                if(!res.success){
                    self_.$message.error(res.message);
                    return ;
                }
                let category=self_.tabList[0];
                category.apps=res.data;
                category.CNT=res.data.length;
                self_.categoryApps();
            })
        },
        //将全部的应用，分类
        categoryApps(){
            let allApps=this.tabList[0].apps;
            for(let app of allApps ){
                let index=this.getIndex(app.categoryId);
                if(index>0){
                    this.tabList[index].apps.push(app);
                }
            }
            this.$forceUpdate();
        },
        //重写父类的刷新表格方法，刷新界面
        refreshGrid(){
            this.loadData();
        },
        tabClick(key){
            this.curKey=key;
        },

        getIndex(key){
            let i=this.tabList.length;
            while(i--){
                if(this.tabList[i].key==key){
                    return  i;
                }
            }
            return -1;
        },
        search(){
            let keyword=this.keyword;
            //循环设置是否显示
            for (var list of this.tabList) {
                var cnt=0
                for(var app of list.apps){
                    if(keyword=='' || app.clientName.indexOf(keyword)>=0){
                        app.hide=false;
                        cnt++;
                    }else{
                        app.hide=true;
                    }
                }
                list.CNT=cnt;
            }
            this.$nextTick(function (){
                this.$forceUpdate();
            });
        },
        mouseleave(){
            this.curAppId = null;
            this.myAppId = null;
        },

        preview(record){
            let url;
            if(record.menuNavType=="1"){
                url=record.path + "/" +record.clientCode;
            }else {
                url= process.env.VUE_APP_ADMIN_FRONT+ "/" +record.clientCode + "/" ;
            }
            window.open(url,"_blank");
        },
    }
}
</script>

<style scoped>
.app_button_list {
    text-align: center;
    padding: 8px;
}
.app_button {
    cursor: pointer;
    border: 1px solid;
    border-radius: 12px;
    padding: 4px 14px;
    color: #1890ff;
}
.app_button_has_install {
    border: 1px solid;
    border-radius: 12px;
    padding: 4px 14px;
    color: #b0b4ba;
}
.app_button:hover {
    background-color: #1890ff;
    color: white;
    border: 1px solid #1890ff;
}
.max_content {
    height: 550px; overflow-y: auto;
}
.app-set li{
    line-height: 30px;
    padding: 0px 20px;
}
.app-set li:hover{
    cursor: pointer;
    color: white;
    background-color: #1890ff;
}
.iconfont-name{
    display: block;
    text-align: center;
    color: white;
    height: 25px;
    line-height: 25px;
    background:rgba(255,255,255,0.2);
    margin-top: -4px;
    font-size: 12px;
    border-radius: 30px 30px 0px 0px;
}
.application{
    width: 100%;
    height: 100%;
    background-color: white;
    padding:20px 0px;
    overflow-x: hidden;
    overflow-y: auto;
}
.application-heard{
    overflow: hidden;
    border-bottom: 1px solid #d9d9d9;
    padding: 0px 20px 20px 20px ;
}
.application-tabb{
    position: relative;
}
.copy{
    position: absolute;
    right: 20px;
    top: 10px;
    font-size: 18px;
    z-index: 9;
}
.copy i:hover{
    color: #1890ff;
    cursor:pointer;
}
.application-LIST{
    width: 130px;
    height:180px;
    float: left;
    border-radius: 10px;
    position: relative;
}
.application-hover{
    padding: 0px 20px;
    display: block;
    margin-top: 20px;
    overflow: hidden;
}
.application-hover>div:hover{
    background-color:rgb(229,229,229);
    cursor: pointer;
}
.application-hover>div:hover .app-icon{
    display: block;
}
.app-icon{
    position: absolute;
    width:calc(100% - 20px);
    top: 10px;
    right: 0px;
    left: 10px;
    display: none;
}
.app-icon >i:nth-child(1){
    float: left;
}
.app-icon >i:nth-child(2){
    float: right;
}
.app-icongont{
    width: 80px;
    height: 80px;
    border-radius: 10px;
    margin: auto;
    padding-top: 15px;
    margin-top: 20px;
    text-align: center;
}
.app-icongont  em{
    font-size: 30px;
    color: white;
}
.app-type{
    text-align: center;
    font-size: 15px;
    margin-top: 10px;
    font-weight: 600;
}
</style>